<template>
  <current>
    <div class="common-container">
      <head-title is-detail title="访视设计" :link-path="linkPath" />
      <div class="content-wrap">
        <div class="header-wrap">
          <div class="common-search ym-box">
            <search-form
              :form="searchForm"
              :center-options="state.centerOptions"
              @search="search"
            />
          </div>
        </div>
        <div class="content">
          <div
            v-loading="state.subLoading"
            class="content-left ym-box"
            :style="{ height: tableHeight + 'px' }"
          >
            <div v-if="state.subjectList.length > 0">
              <div
                v-for="item in state.subjectList"
                :key="item.subId"
                class="info-item"
                @click="clickSub(item)"
              >
                <base-info :info="item" :class="{ 'is-active': state.currentSub === item.subId }" />
              </div>
            </div>
            <empty-block v-else />
          </div>
          <div
            v-loading="state.visitLoading"
            class="content-right ym-box"
            :style="{ height: tableHeight + 'px' }"
          >
            <div class="search-wrap">
              <el-form :model="visitSearchForm" inline size="mini">
                <el-form-item>
                  <select-form
                    v-model="visitSearchForm.visit"
                    :options="visitOptions"
                    :default-props="{ label: 'label', value: 'value' }"
                    :multiple="false"
                  />
                </el-form-item>
              </el-form>
              <div>
                <el-button type="primary" size="mini" style="height: 28px" @click="addVisit"
                  >新访视</el-button
                >
              </div>
            </div>
            <div v-if="state.visitList.length > 0">
              <el-row :gutter="10" class="visit-list">
                <el-col
                  v-for="item in state.visitList"
                  :key="item.vid"
                  class="visit-item"
                  :class="{ 'is-active': state.currentVisit.vid === item.vid }"
                >
                  <visit-item :info="item" @click="clickVisit(item)" />
                </el-col>
              </el-row>
              <div v-if="state.visitList.length > 0" class="visit-info-box">
                <div class="btn-wrap">
                  <el-button type="primary" size="small">编辑</el-button>
                  <el-button
                    type="primary"
                    size="small"
                    :disabled="
                      state.currentVisit.issuesStatus === ISSUES_STATUS_MAP.wancheng ||
                      state.currentVisit.issuesStatus === ISSUES_STATUS_MAP.zhengchang
                    "
                    @click="addViewer"
                    >上传影像</el-button
                  >
                  <el-button type="primary" size="small" :disabled="submitDisabled" @click="submit"
                    >提交评估</el-button
                  >
                  <el-button
                    type="primary"
                    size="small"
                    @click="getVisitDicomData(state.currentVisit.vid)"
                    >刷新</el-button
                  >
                </div>
                <detail-info :detail="state.currentVisit" />
                <viewer-info
                  v-loading="state.dicomLoading"
                  :detail="(state.dicomList?.length > 0 && state.dicomList[0]) || null"
                />
              </div>
            </div>
            <div v-else style="height: 200px">
              <empty-block />
            </div>
          </div>
        </div>
      </div>
    </div>
    <add-dialog
      v-model:visible="state.dialogVisible"
      :sub-id="state.currentSub"
      @search="handleAddSuccess"
    />
    <add-viewer-dialog
      v-model:visible="state.viewerDialogVisible"
      :project-id="pid"
      :centre-id="state.centreId"
      :visit-id="state.currentVisit.vid"
      @search="getVisitDicomData(state.currentVisit.vid)"
    />
  </current>
</template>

<script lang="ts" setup>
import { computed, reactive, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import { ElMessage } from 'element-plus'

import BaseInfo from '../components/BaseInfo.vue'
import EmptyBlock from '@/components/EmptyBlock/index.vue'
import SelectForm from '@/components/Form/Select.vue'
import HeadTitle from '@/components/HeaderTitle/index.vue'
import Current from '../../current/index.vue'
import SearchForm from '../searchForm.vue'
import AddDialog from './addDialog.vue'
import AddViewerDialog from './addViewerDialog.vue'
import CheckCard from './checkCard.vue'
import VisitItem from './visitCard.vue'
import DetailInfo from './visitInfo/detail.vue'
import ViewerInfo from './visitInfo/viewer.vue'

import { getOrgClsListByPid, orgType } from '@/api/common'
import SubjectApi from '@/api/subject'
import { getVisitDicom, getVisitList, submitVisit, updateVisitRemark } from '@/api/visit'

import { useTable } from '@/utils/common/useTable'

import { ISSUES_STATUS_MAP } from '@/configs/codeMaps'
import IBaseObj from '#/index'

const { tableHeight } = useTable()

const route = useRoute()
const router = useRouter()
const { pid, pname, subId }: IBaseObj = route.query

const linkPath = `/project/visit?pid=${pid}&pname=${pname}`

const state: IBaseObj = reactive({
  centerOptions: [],
  currentSub: 0,
  centreId: 0,
  subLoading: false,
  subjectList: [],
  visitList: [],
  visitLoading: false,
  currentVisit: {},
  dicomList: [],
  dialogVisible: false,
  viewerDialogVisible: false,
  dicomLoading: false,
})

const submitDisabled = computed(() => {
  return (
    state.dicomList?.length === 0 || state.currentVisit.issuesStatus !== ISSUES_STATUS_MAP.daitijiao
  )
})

const searchForm = reactive({
  centreId: '',
  sic: '',
  inTimeBegin: '',
  inTimeEnd: '',
})

const visitSearchForm = reactive({
  visit: 'all',
})

const visitOptions = [
  {
    label: '所有访视',
    value: 'all',
  },
]

watch(
  () => state.currentSub,
  (val) => {
    if (val) {
      getVisitDetail(val)
      router.push(`/project/visit/detail?pid=${pid}&pname=${pname}&subId=${val}`)
    } else {
      state.visitList = []
      router.push(`/project/visit/detail?pid=${pid}&pname=${pname}`)
    }
  }
)

watch(
  () => state.currentVisit.vid,
  (val) => {
    if (val) {
      state.dicomList = []
      getVisitDicomData(val)
    } else {
      state.dicomList = []
    }
  }
)

const addVisit = () => {
  state.dialogVisible = true
}
// 添加访视成功
const handleAddSuccess = () => {
  search(false, false)
  searchVisit()
}

// 提交
const submit = async () => {
  const ret = await submitVisit(state.currentVisit.vid)
  if (ret.data) {
    ElMessage({ message: '提交成功！', type: 'success' })
    // 手动更新状态为待核查
    state.currentVisit.issuesStatus = ISSUES_STATUS_MAP.daihecha
  }
}

const addViewer = () => {
  state.viewerDialogVisible = true
}

const getVisitDetail = async (subId: string) => {
  state.visitLoading = true
  try {
    const ret = await getVisitList(subId)
    state.visitList = ret.data || []

    if (state.visitList.length > 0) {
      state.currentVisit = state.visitList[0]
    }
  } finally {
    state.visitLoading = false
  }
}

const searchVisit = () => {
  getVisitDetail(state.currentSub)
}

// 初始将选中的数据变为第一条数据
const formatSubject = () => {
  const index = state.subjectList.findIndex((v: IBaseObj) => v.subId === subId * 1)
  const item = state.subjectList[index]
  state.subjectList.splice(index, 1)
  item && state.subjectList.unshift(item)
}

// 初始化查询
const initSearch = async () => {
  search(true)
}

/**
 * isInit 是否是初始查询
 * needInit 是否需要设置第一个值
 */
const search = async (isInit = false, needInit = true) => {
  state.subLoading = true
  try {
    const ret = await SubjectApi.getListSubject({ ...searchForm, pid })
    state.subjectList = ret.data || []
    if (isInit) {
      formatSubject()
    }

    if (state.subjectList?.length > 0) {
      if (needInit) {
        state.currentSub = state.subjectList[0].subId
        state.centreId = state.subjectList[0].centreId
      }
    } else {
      state.currentSub = 0
      state.centreId = 0
    }
  } finally {
    state.subLoading = false
  }
}

const clickSub = (val: IBaseObj) => {
  const lastSub = state.currentSub
  if (lastSub === val.subId) {
    return
  }
  state.currentSub = val.subId
  state.centreId = val.centreId
}

const clickVisit = (val: IBaseObj) => {
  const lastSub = state.currentVisit
  if (lastSub.vid === val.vid) {
    return
  }
  state.currentVisit = val
}

const getVisitDicomData = async (vid: string) => {
  state.dicomLoading = true
  try {
    const ret = await getVisitDicom(vid)
    state.dicomList = ret.data
  } finally {
    state.dicomLoading = false
  }
}

/* remark start */
const remarkState = reactive({
  remark: '',
  visible: false,
})

const addRemark = () => {
  remarkState.visible = true
  remarkState.remark = state.currentVisit.remark
}

const cancelRemark = () => {
  remarkState.visible = false
  remarkState.remark = ''
}

const submitRemark = async () => {
  const ret = await updateVisitRemark({
    remark: remarkState.remark,
    vid: state.currentVisit.vid * 1,
  })
  if (ret) {
    state.currentVisit.remark = remarkState.remark
    remarkState.visible = false
  }
}
/* remark end */

const getCenterOptions = async () => {
  const ret = await getOrgClsListByPid(pid, orgType.yjdw)
  state.centerOptions = ret.data
}
const init = () => {
  initSearch()
  getCenterOptions()
}
init()
</script>

<style lang="scss" scoped>
.btn-wrap {
  margin: 10px 0;
}

.search-wrap {
  display: flex;
  justify-content: space-between;
  text-align: right;
}

.content {
  display: flex;

  & > div {
    height: calc(100vh - 80px);
    overflow: auto;
    @include scroll-bar;
  }

  &-left {
    display: flex;
    justify-content: center;
    width: 25%;
    min-width: 340px;
    padding: 20px 15px;
    // padding: 20px 15px;
    // margin-right: 15px;
    border-right: 1px solid var(--table-border);
    border-radius: 6px 0 0 6px;

    .info-item {
      display: flex;
      width: 300px;
      height: 200px;
      flex-direction: column;
      justify-content: center;

      & + .info-item {
        margin-top: 10px;
      }
    }
  }

  &-right {
    flex: 1;
    padding: 20px 15px;
    border-radius: 0 6px 6px 0;
  }
}

.visit {
  &-list {
    flex-wrap: wrap;
  }

  &-item {
    flex-basis: auto;
    margin-bottom: 10px;
  }
}

.visit-info-box {
  .visit {
    &-title {
      padding-left: 4px;
      font-size: 22px;
      font-weight: 600;
      line-height: 40px;
      color: #f9b034;

      &-wrap {
        display: flex;
        height: 40px;
        align-items: center;
        justify-content: space-between;
        // justify-content: flex-end;
      }
    }

    &-info {
      display: flex;
    }
  }

  .icon {
    position: absolute;
    top: 6px;
    right: 6px;
  }

  .check {
    &-list {
      flex: 1;
    }
  }

  .other {
    &-info {
      width: 20%;
      min-width: 200px;
      margin-left: 10px;
    }

    &-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      // height: 80px;
      padding: 15px 20px;
      margin-bottom: 10px;
      background: var(--background-color-1);
      border-radius: 6px;

      &__title {
        margin-bottom: 15px;
        line-height: 24px;
      }

      &__time {
        font-size: 16px;
        color: var(--color-2);
      }
    }
  }

  .remark-item {
    flex-direction: column;
    align-items: flex-start;

    .remark-content {
      word-break: break-all;
    }

    .other-item__title {
      display: flex;
      width: 100%;
      margin-bottom: 15px;
      align-items: center;
      justify-content: space-between;

      .el-icon {
        font-size: 16px;
        cursor: pointer;
      }
    }

    .remark-btn {
      margin-top: 5px;
      text-align: right;
    }
  }
}

.add-dicom-card {
  display: flex;
  padding: 20px 0;
  margin-bottom: 10px;
  font-size: 18px;
  cursor: pointer;
  background: var(--background-color-1);
  border-radius: 6px;
  justify-content: center;
  align-items: center;

  .el-icon {
    margin-right: 5px;
    font-size: 18px;
  }
}
</style>
